package com.qx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

/**
 * 描述：<br>
 * 公用函数
 * 
 * @author mynff@sina.cn
 * @date 2014-2-11
 */
public final class AppFunction {

	private AppFunction() {
	}

	/**
	 * @author mynff@sina.cn 描述:<br>
	 *         int转换成byte数组
	 * @param i
	 * @return
	 */
	public static byte[] intToByteArray(int i) {
		byte[] result = new byte[4];
		result[0] = (byte) ((i >> 24) & 0xFF);
		result[1] = (byte) ((i >> 16) & 0xFF);
		result[2] = (byte) ((i >> 8) & 0xFF);
		result[3] = (byte) (i & 0xFF);
		return result;
	}

	/**
	 * @author mynff@sina.cn 描述:<br>
	 *         byte数组转换成int
	 * @param bytes
	 * @return
	 */
	public static int byteArrayToInt(byte[] bytes) {
		int value = 0;
		// 由高位到低位
		for (int i = 0; i < 4; i++) {
			int shift = (4 - 1 - i) * 8;
			value += (bytes[i] & 0x000000FF) << shift;
		}
		return value;
	}

	/**
	 * 描述：<br>
	 * 读取xml
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static Document readXml(String path) throws Exception {
		SAXReader saxReader = new SAXReader();
		ClassLoader loader = AppFunction.class.getClassLoader();
		String uri = "";
		try {
			uri = loader.getResource("/").getPath() + path;
		} catch (Exception e) {
			uri = System.getProperty("user.dir") + "/" + path;
		}
		File file = new File(uri);
		if (!file.exists())
			throw new Exception("读取的xml不存在");
		FileInputStream in = new FileInputStream(file);
		Reader reader = new InputStreamReader(in, "utf-8");
		return saxReader.read(reader);
	}

}
